import os
import sys
import pandas as pd
import datetime
from MainConsolidator import MainConsolidator

class handler(object):
    @staticmethod
    def module_name():
        return 'Штрипс ТЭСЦ-3'
    @staticmethod
    def handle(row:pd.Series,consolidator:MainConsolidator)->pd.Series:
        try:
            product = row["Первичный продукт"]
            gmsps = row["ГМСПС"]
            thickness = row["Толщина, мм <Производство>"]
            width_led = consolidator.nearest_in_guid("Параметры по Продукту ТЭСЦ-3",
                f"`Производство`=='Штрипс ТЭСЦ-3' and `Продукт`=='{product}' and `Доп параметр2` == '{gmsps[:2]}'",
                "Доп параметр1",
                row["Ширина штрипса, мм <Производство>"],
                "Доп параметр1")
            width_led_s=str(width_led).replace(".0","")
            product_up = None
            thickness_range = None
            if "ГУ" in gmsps:
                thickness_range = consolidator.scalar_in_guid("Параметры по Продукту ТЭСЦ-3",
                    f"`Производство`=='Штрипс ТЭСЦ-3' and `Продукт`=='{product}' and `Доп параметр2` == 'ГУ' and `Мин`<={thickness}<=`Макс`","Диапазон")
                product_up=f"{product} {thickness_range} Ш{width_led_s} ГУ"
            else:
                product_up=f"{product} Ш{width_led_s} {gmsps}"
            print(f"product: {product}; thickness: {thickness}; width_led: {width_led_s}; thickness_range: {thickness_range}")
            row["error"] = pd.NA
        except Exception as exp: 
            row["error"] = f"{exp}"
        finally:
            row["Продукт УП"]=product_up
            row["Время укрупнения"]=datetime.datetime.now()
            return row
        
    def debug_handle(self,inputDf:pd.DataFrame,consolidator:MainConsolidator,module:str=None)->pd.DataFrame:
        try:
            if module is None: return inputDf.apply(lambda row: self.handle(row,consolidator), axis=1)
            else: return inputDf[inputDf["Производство2"]==module].apply(lambda row: self.handle(row,consolidator), axis=1)
        except: raise
    
    def get_compiled(self):
        code:str=f"print('{__file__}')"
        try:
            with open(__file__,encoding="utf-8",mode="r") as f:
                code=f.read()
        except Exception as exp: 
            code=f"print('error: {exp}')"
        finally:
            cc = compile(code,"","exec")
            return cc

if __name__=="__strips_t3__":
    consolidator:MainConsolidator
    record:pd.Series
    result:pd.Series
    result = handler.handle(record,consolidator)

